import { create } from 'zustand'
import { createSelectors } from '@/utils/createSelectors'

interface ImageData {
  pid: number
  p: number
  uid: number
  title: string
  author: string
  urls: {
    original: string
  }
}

interface ImageState {
  images: ImageData[]
  loading: boolean
  error: string | null
  // 异步方法
  fetchImages: () => Promise<void>
}

const useImageStoreBase = create<ImageState>()((set) => ({
  images: [],
  loading: false,
  error: null,

  fetchImages: async () => {
    try {
      set({ loading: true, error: null })
      
      const response = await fetch('/api/images')
      if (!response.ok) {
        throw new Error('网络请求失败')
      }
      
      const data = await response.json()
      set({ images: data.data, loading: false })
    } catch (error) {
      set({ 
        error: error instanceof Error ? error.message : '发生未知错误',
        loading: false 
      })
    }
  }
}))

const useImageStore = createSelectors(useImageStoreBase)

export default useImageStore 